package servlet.videostream;

import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameGrabber;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * servlet.videostream
 * User: 邱
 * Date: 2024/12/24 13:24
 * Description:
 * Version: V1.0
 */
@WebServlet("/video-stream")
public class VideoStreamServlet extends HttpServlet {
    private OpenCVFrameGrabber grabber;

    @Override
    public void init() throws ServletException {
        grabber = new OpenCVFrameGrabber(0); // 0代表默认摄像头
        try {
            grabber.start();
        } catch (FrameGrabber.Exception e) {
           e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/jpeg");
        try {
            Frame frame = grabber.grab();
            if (frame != null) {
                Java2DFrameConverter converter = new Java2DFrameConverter();
                BufferedImage bufferedImage = converter.convert(frame);
                try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream();){
                    ImageIO.write(bufferedImage, "jpg", outputStream);
                    resp.getOutputStream().write(outputStream.toByteArray());
                }
            }
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        try {
            if (grabber != null) {
                grabber.stop();
            }
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        }
    }
}
